#!/bin/bash

BASE_PATH=$HOME/.mara
MYSQL_NAME="sec-mysql"

getSecurity() {
    cat $BASE_PATH/security.json | jq -r "$1"
}

get_secrets() {
  if [ ! -f $BASE_PATH/security.json ]; then
    echo "Please create security.json file first"
    exit 1
  fi

  # mysql root password
  mysql_root_password=$(getSecurity ".mysql.root")
  if [ -z $mysql_root_password ] || [ $mysql_root_password == "null" ]; then
    echo "Not found root password in security.json"
    exit 1
  fi

  # mysql user password
  mysql_user_password=$(getSecurity ".mysql.user")
  if [ -z $mysql_user_password ] || [ $mysql_user_password == "null" ]; then
    echo "Not found user password in security.json"
    exit 1
  fi
}

expand_vars() {
  source_file=$1
  target_file=$2
  if sed \
\
-e s\`'$ENV::mysql_user_password'\`\
"$mysql_user_password"\`g \
\
	"$source_file" > "$target_file"
  then
    : # ok
  else
    return 1
  fi
}

run_sql() {
    tmpfile=$(mktemp)
    expand_vars $1 $tmpfile
    docker exec -i $MYSQL_NAME mysql -uroot -p$mysql_root_password < $tmpfile
    rm -f $tmpfile
}

if [ $# -eq 0 ]; then
  echo "Usage: ./scripts/runsql.sh <sql_file>"
  exit 1
fi

if [ -f $1 ]; then
    get_secrets
    run_sql $1
else
  echo "File $1 not found"
  exit 1
fi
